package com.ec.as.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ec.api.client.ElderProfileClient;
import com.ec.as.domain.po.LeaveRequest;
import com.ec.as.mapper.LeaveRequestMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Configuration
@RequiredArgsConstructor
public class LeaveStatusTask {
    private final LeaveRequestMapper leaveRequestMapper;
    private final ElderProfileClient elderProfileClient;

    /**
     * 每半小时检查请假开始时间，更新老人状态为"临时外出"
     */
    @Scheduled(cron = "0 0/30 * * * ?") // 每半小时执行（0秒0分、30分）
    public void updateToOnLeaveStatusTask() {
        try {
            // 查询状态为已批准且开始时间在当前时间附近的记录
            LocalDateTime now = LocalDateTime.now();
            LambdaQueryWrapper<LeaveRequest> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(LeaveRequest::getStatus, "approved")
                    .le(LeaveRequest::getStartTime, now)
                    .gt(LeaveRequest::getEndTime, now); // 确保请假未结束
            List<LeaveRequest> leaveRequests = leaveRequestMapper.selectList(wrapper);

            for (LeaveRequest request : leaveRequests) {
                try {
                    // 调用profile-service检查老人当前状态
                    Long userId = request.getElderlyUserId();

                    // 调用FeignClient更新老人状态为"临时外出"
                    elderProfileClient.updateElderlyStatusByUserId(userId, "临时外出");

                    log.info("已将老人用户{}状态更新为'临时外出'，请假请求ID：{}", userId, request.getId());
                } catch (Exception e) {
                    log.error("更新请假请求{}状态为'临时外出'失败：{}", request.getId(), e.getMessage());
                }
            }
        } catch (Exception e) {
            log.error("updateToOnLeaveStatusTask任务执行出错：{}", e.getMessage());
        }
    }

    /**
     * 每半小时检查请假结束时间，更新老人状态为"在住"
     */
    @Scheduled(cron = "0 0/30 * * * ?") // 每半小时执行（0秒0分、30分）
    public void updateToCheckInStatusTask() {
        try {
            // 查询状态为临时外出且结束时间已到达的记录
            LocalDateTime now = LocalDateTime.now();
            LambdaQueryWrapper<LeaveRequest> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(LeaveRequest::getStatus, "on_leave")
                    .le(LeaveRequest::getEndTime, now);
            List<LeaveRequest> leaveRequests = leaveRequestMapper.selectList(wrapper);

            for (LeaveRequest request : leaveRequests) {
                try {
                    // 调用FeignClient更新老人状态为"在住"
                    Long userId = request.getElderlyUserId();
                    elderProfileClient.updateElderlyStatusByUserId(userId, "在住");

                    log.info("已将老人用户{}状态更新为'在住'，请假请求ID：{}", userId, request.getId());
                } catch (Exception e) {
                    log.error("更新请假请求{}状态为'在住'失败：{}", request.getId(), e.getMessage());
                }
            }
        } catch (Exception e) {
            log.error("updateToCheckInStatusTask任务执行出错：{}", e.getMessage());
        }
    }

    /**
     * 测试任务，每5秒执行一次
     */
//    @Scheduled(cron = "0/5 * * * * ?") // 每5秒执行
//    public void testTask() {
//        try {
//            log.info("测试任务执行时间：{}", LocalDateTime.now());
//        } catch (Exception e) {
//            log.error("testTask任务执行出错：{}", e.getMessage());
//        }
//    }
}
